package com.niiwoo.civet.mobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.mobile.vo.request.*;
import com.niiwoo.civet.mobile.vo.request.user.SocialAuthRequestVO;
import com.niiwoo.civet.mobile.vo.response.FadadaEnterAuthNonIgnoreResponseVO;
import com.niiwoo.civet.mobile.vo.response.user.*;
import com.niiwoo.civet.snapdata.dto.response.SocialSecurityInfoRespDTO;
import com.niiwoo.civet.snapdata.dto.response.SocialSecurityRecordDTO;
import com.niiwoo.civet.snapdata.service.SocialSecurityDataDubboService;
import com.niiwoo.civet.user.dto.request.DataStatusRequestDTO;
import com.niiwoo.civet.user.dto.response.DataStatusResponseDTO;
import com.niiwoo.civet.user.dto.response.ThirdAuthResponseDTO;
import com.niiwoo.civet.user.dto.response.UserAuthorizationInfoResponseDTO;
import com.niiwoo.civet.user.dto.response.ZhiMaScoreResponseDTO;
import com.niiwoo.civet.user.enums.UserDataStatusEnum;
import com.niiwoo.civet.user.enums.UserDataTypeEnum;
import com.niiwoo.civet.user.service.*;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import com.niiwoo.tripod.provider.exception.BizException;
import com.niiwoo.tripod.web.annotation.AuthIgnore;
import com.niiwoo.tripod.web.shiro.UserAuthPrincipal;
import com.niiwoo.tripod.web.util.PrincipalContext;
import com.niiwoo.tripod.web.util.RequestUtil;
import com.niiwoo.tripod.web.vo.Empty;
import com.niiwoo.tripod.web.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

/**
 * @Description: 用户授权
 * @Author:LiJian
 * @Date:2017/10/12
 */
@Slf4j
@RestController
@RequestMapping("/userAuth")
@Api(tags = "用户授权(李健)", description = "/userAuth")
public class UserAuthorizationController extends BaseController {
    @Reference(version = "1.0.0")
    private UserAuthorizationInfoDubboService userAuthorizationInfoDubboService;
    @Reference(version = "1.0.0")
    private UserStatusDubboService userStatusDubboService;

    @Reference(version = "1.0.0")
    private UserAuthOperatorDubboService userAuthOperatorDubboService;

    @Reference(version = "1.0.0")
    private UserAuthCreditCardDubboService userAuthCreditCardDubboService;


    @Reference(version = "1.0.0")
    private UserAuthSocialDubboService userAuthSocialDubboService;

    @Reference(version = "1.0.0")
    private UserAuthZhiMaDubboService userAuthZhiMaDubboService;

    @Reference(version = "1.0.0")
    private UserAuthEducationDubboService userAuthEducationDubboService;

    @Reference(version = "1.0.0")
    private UserAuthJdDubboService userAuthJdDubboService;

    @Reference(version = "1.0.0")
    private SocialSecurityDataDubboService socialSecurityDataDubboService;

    @Reference(version = "1.0.0")
    private UserBasicInfoDubboService userBasicInfoDubboService;

    @Autowired
    PrivacyMasks privacyMasks;

    @PostMapping("/userZhiMaInfo")
    @ApiOperation("用户芝麻信息")
    public Result<UserZhimaInfoResponseDTO> userZhimaInfo() {
        UserAuthPrincipal principal = (UserAuthPrincipal) SecurityUtils.getSubject().getPrincipal();
        String userId = principal.getUserId();
        UserZhimaInfoResponseDTO userZhimaInfoResponseDTO = new UserZhimaInfoResponseDTO();

        DataStatusResponseDTO dataStatusResponseDTO = userStatusDubboService.getByUserIdAndType(userId, UserDataTypeEnum.ZHIMA_AUTHORIZE);
        UserAuthorizationInfoResponseDTO userAuthorizationInfo = userAuthorizationInfoDubboService.getUserAuthorizationInfo(userId);
        if (dataStatusResponseDTO == null
                || userAuthorizationInfo == null) {
            //未认证
            userZhimaInfoResponseDTO.setAuthStatus(UserDataStatusEnum.ZhimaCreditStatus.NOAPPLY.getStatus().intValue());
            return Result.with(userZhimaInfoResponseDTO);
        }
        //拼装返回参数
        userZhimaInfoResponseDTO.setAuthStatus(dataStatusResponseDTO.getDataStatus().intValue());
        if (dataStatusResponseDTO.getAuthTime() != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userZhimaInfoResponseDTO.setAuthTime(sdf.format(dataStatusResponseDTO.getAuthTime()));
        }
        userZhimaInfoResponseDTO.setFailMsg(mappingZhiMaErrorMsg(userAuthorizationInfo.getZhimaFailureReason()));
        userZhimaInfoResponseDTO.setZhimaScore(userAuthorizationInfo.getZhimaScore());

        return Result.with(userZhimaInfoResponseDTO);


    }

    /**
     * 返回错误信息
     *
     * @param msg
     * @return
     */
    private String mappingZhiMaErrorMsg(String msg) {
        switch (msg) {
            case "你对应的支付宝账号非个人用户或者非身份证认证":
                return "请先将支付宝账户进行实名认证";
            case "支付宝账号不存在":
                return "请先开通实名认证的支付宝账户";
            case "请重新登录支付宝再试":
                return "请重新登录支付宝再试";
            case "授权模式不存在":
                return "请联系芝麻信用技术支持配置授权模式";
            case "姓名身份证不匹配":
                return "请输入正确的身份信息";
            case "不支持的证件年龄":
                return "请确认当前用户年龄超过16岁，确认后请重新发起请求";
            case "仅支持身份证作为核身证件":
                return "请确认当前输入的证件信息必须为身份证信息";
            case "参数不正确":
                return "请根据提示修正参数";
            case "非法商户授权等级":
                return "请联系技术支持";
            case "ZMCSP.mobile_unbound":
                return "请先绑定手机";
            case "系统错误，稍后再试":
                return "系统错误，稍后再试";
            case "注册失败":
                return "请联系技术支持";
            case "身份证后四位输入错误超过限，请24小时后重试":
                return "请24小时后重试";
            default:
                return msg;
        }
    }


    @PostMapping("/getFadadaStatus")
    @ApiOperation("法大大授权状态")
    public Result<FadadaStatusResponseVO> getFadadaStatus() {
        String userId = PrincipalContext.getUserId();
        log.info("getFadadaStatus.userId={}",userId);
        DataStatusResponseDTO dataStatusResponseDTO = userStatusDubboService.getByUserIdAndType(userId, UserDataTypeEnum.FADADA_AUTHORIZE);
        FadadaStatusResponseVO vo = new FadadaStatusResponseVO();
        if(dataStatusResponseDTO==null || UserDataStatusEnum.FadadaStatus.NOT_CERTIFIED.getStatus().byteValue()==dataStatusResponseDTO.getDataStatus().byteValue()){
            vo.setFadadaStatus(UserDataStatusEnum.FadadaStatus.NOT_CERTIFIED.getStatus());
        }else{
            vo.setFadadaStatus(UserDataStatusEnum.FadadaStatus.PASS_CERTIFIED.getStatus());
        }
        log.info("getFadadaStatus.userId={},vo={}",userId, JSON.toJSONString(vo));
        return Result.with(vo);
    }

    @PostMapping("/fadadaAuth")
    @ApiOperation("法大大授权")
    public Empty fadadaAuth() {
        String userId = PrincipalContext.getUserId();
        log.info("fadadaAuth.userId={}",userId);
        userAuthorizationInfoDubboService.fadadaAuth(userId);
        log.info("fadadaAuth.userId={} end",userId);
        return Empty.getInstance();
    }

    @PostMapping("/fadadaAuthNonIgnore")
    @ApiOperation("法大大授权-无需登录")
    @AuthIgnore
    public Empty fadadaAuthNonIgnore(@RequestBody @Valid FadadaAuthNonIgnoreRequestVO requestVO) {
        log.info("fadadaAuthNonIgnore.requestVO={}",JSON.toJSONString(requestVO));
        String mobileNo = requestVO.getMobileNo();

        log.info("fadadaAuthNonIgnore.mobileNo={}",mobileNo);

        String userId = userBasicInfoDubboService.queryUserIdByMobileNo(mobileNo);

        log.info("fadadaAuthNonIgnore.userId={}",userId);

        if(StringUtils.isEmpty(userId)){
            throw new BizException("USR10028");
        }

        userAuthorizationInfoDubboService.fadadaAuth(userId);
        log.info("fadadaAuthNonIgnore.mobileNo={} end",mobileNo);
        return Empty.getInstance();
    }

    @PostMapping("/operatorAuth")
    @ApiOperation("手机运营商授权")
    public Result<ThirdAuthResponseVO> operatorAuth(HttpServletRequest httpServletRequest) {
        String userId = PrincipalContext.getUserId();
        String createIp = RequestUtil.getUserRealIP(httpServletRequest);
        log.info("operatorAuthCreateIp:" + createIp);
        ThirdAuthResponseDTO thirdAuthResponseDTO = userAuthOperatorDubboService.getThirdAuthUrl(userId, createIp);
        if (thirdAuthResponseDTO == null) {
            return Result.with(null);
        }
        ThirdAuthResponseVO vo = new ThirdAuthResponseVO();
        BeanUtils.copyProperties(thirdAuthResponseDTO, vo);
        vo.setStatus(NumberUtils.toInt(thirdAuthResponseDTO.getStatus()));
        if(thirdAuthResponseDTO.getUserDataStatus() != null) {
            vo.setUserDataStatus(Integer.valueOf(thirdAuthResponseDTO.getUserDataStatus()));
        }
        return Result.with(vo);
    }

    @PostMapping("/getOperatorStatus")
    @ApiOperation("获取运营商授权状态")
    public Result<OperatorAuthResponseVO> getOperatorStatus() {
        String userId = PrincipalContext.getUserId();
        DataStatusResponseDTO dataStatusResponseDTO = userStatusDubboService.getByUserIdAndType(userId, UserDataTypeEnum.OPERATOR_AUTHORIZE);
        OperatorAuthResponseVO vo = new OperatorAuthResponseVO();
        if (dataStatusResponseDTO == null) {
            vo.setStatus(UserDataStatusEnum.PhoneOperatorStatus.NOCREDIT.getStatus());
            vo.setDesc(UserDataStatusEnum.PhoneOperatorStatus.NOCREDIT.getDesc());
        } else {
            vo.setStatus(dataStatusResponseDTO.getDataStatus());
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            vo.setAuthTime(format.format(dataStatusResponseDTO.getAuthTime()));
            UserDataStatusEnum.PhoneOperatorStatus byStatus = UserDataStatusEnum.PhoneOperatorStatus.getByStatus(dataStatusResponseDTO.getDataStatus());
            if (byStatus != null) {
                vo.setDesc(byStatus.getDesc());
            }
        }
        return Result.with(vo);
    }

    @PostMapping("/socialSecurityAuth")
    @ApiOperation("社保授权")
    public Result<ThirdAuthResponseVO> socialSecurityAuth(@RequestBody(required = false) SocialAuthRequestVO socialAuthRequestVO, HttpServletRequest httpServletRequest) {
        String userId = PrincipalContext.getUserId();
        String createIp = RequestUtil.getUserRealIP(httpServletRequest);
        if(socialAuthRequestVO == null){
            socialAuthRequestVO = new SocialAuthRequestVO();
        }
        log.info("socialSecurityAuthCreateIp:" + createIp + ",city:" + socialAuthRequestVO.getCity());
        ThirdAuthResponseDTO thirdAuthResponseDTO = userAuthSocialDubboService.getThirdAuthUrl(userId, createIp, socialAuthRequestVO.getCity());
        if (thirdAuthResponseDTO == null) {
            return Result.with(null);
        }
        ThirdAuthResponseVO vo = new ThirdAuthResponseVO();
        BeanUtils.copyProperties(thirdAuthResponseDTO, vo);
        vo.setStatus(NumberUtils.toInt(thirdAuthResponseDTO.getStatus()));
        if(thirdAuthResponseDTO.getUserDataStatus() != null) {
            vo.setUserDataStatus(Integer.valueOf(thirdAuthResponseDTO.getUserDataStatus()));
        }
        return Result.with(vo);
    }

    @PostMapping("/getSocialSecurityStatus")
    @ApiOperation("获取社保授权状态")
    public Result<SocialSecurityInfoResponseVO> getSocialSecurityStatus() {
        String userId = PrincipalContext.getUserId();
        DataStatusResponseDTO dataStatusResponseDTO = userStatusDubboService.getByUserIdAndType(userId, UserDataTypeEnum.SOCIAL_SECURITY_OPERATOR_AUTHORIZE);
        SocialSecurityInfoResponseVO vo = new SocialSecurityInfoResponseVO();
        if (dataStatusResponseDTO == null) {
            vo.setSocialAuthStatus(UserDataStatusEnum.SocialSecurityStatus.NOCREDIT.getStatus());
        } else {
            vo.setSocialAuthStatus(dataStatusResponseDTO.getDataStatus());
        }
        return Result.with(vo);
    }

    @PostMapping("/zhiMaAuth")
    @ApiOperation("获取芝麻授权H5页面链接")
    public Result<ThirdAuthResponseVO> zhiMaAuth(HttpServletRequest httpServletRequest) {
        String userId = PrincipalContext.getUserId();
        String createIp = RequestUtil.getUserRealIP(httpServletRequest);
        log.info("zhiMaAuthCreateIp:" + createIp);
        ThirdAuthResponseDTO thirdAuthResponseDTO = userAuthZhiMaDubboService.getThirdAuthUrl(userId, createIp);
        if (thirdAuthResponseDTO == null) {
            return Result.with(null);
        }
        ThirdAuthResponseVO vo = new ThirdAuthResponseVO();
        BeanUtils.copyProperties(thirdAuthResponseDTO, vo);
        vo.setStatus(NumberUtils.toInt(thirdAuthResponseDTO.getStatus()));
        return Result.with(vo);
    }

    @PostMapping("/flushZhiMaScore")
    @ApiOperation("获取芝麻分")
    public Result<ZhiMaScoreResponseDTO> flushZhiMaScore(HttpServletRequest httpServletRequest) {
        String userId = PrincipalContext.getUserId();
        ZhiMaScoreResponseDTO zhiMaScoreResponseDTO = userAuthZhiMaDubboService.getZhiMaScore(userId);
        if (zhiMaScoreResponseDTO == null) {
            return Result.with(null);
        }
        return Result.with(zhiMaScoreResponseDTO);
    }

    @PostMapping("/getSocialSecurityDetail")
    @ApiOperation("获取社保详细信息:用户信息及6个月的缴费记录")
    public Result<SocialSecurityResponseDetailVO> getSocialSecurityDetail(HttpServletRequest httpServletRequest) {
        String userId = PrincipalContext.getUserId();
        DataStatusResponseDTO dataStatusResponseDTO = userStatusDubboService.getByUserIdAndType(userId, UserDataTypeEnum.SOCIAL_SECURITY_OPERATOR_AUTHORIZE);

        if (dataStatusResponseDTO == null) {
            SocialSecurityResponseDetailVO vo = new SocialSecurityResponseDetailVO();
            vo.setStatus(UserDataStatusEnum.SocialSecurityStatus.NOCREDIT.getStatus());
            return Result.with(vo);
        } else {
            SocialSecurityResponseDetailVO vo = this.querySocialSecurity(userId);
            if(vo != null) {
                vo.setStatus(dataStatusResponseDTO.getDataStatus());
            }else{
                vo = new SocialSecurityResponseDetailVO();
                vo.setStatus(dataStatusResponseDTO.getDataStatus());
                return Result.with(vo);
            }
            return Result.with(vo);
        }

    }


    /**
     * 拼接按页面的内容结构
     *
     * @param userId
     * @return
     */
    private SocialSecurityResponseDetailVO querySocialSecurity(String userId) {

        SocialSecurityInfoRespDTO socialSecurityInfo = socialSecurityDataDubboService.querySocialSecurityInfo(userId);
        if (socialSecurityInfo == null) {
            return null;
        }


        SocialSecurityResponseDetailVO responseDTO = new SocialSecurityResponseDetailVO();

        //查询用户信息
        SocialSecurityResponseDetailVO.UserInfo userInfo = new SocialSecurityResponseDetailVO.UserInfo();
        BeanUtils.copyProperties(socialSecurityInfo, userInfo);
        userInfo.setBaseNumber(socialSecurityInfo.getBaseNumber().toString());

        if(socialSecurityInfo.getLastPayDate() != null){
            userInfo.setLastPayDate(DateFormatUtils.format(socialSecurityInfo.getLastPayDate(), "yyyy-MM-dd"));
        }

        if (StringUtils.isNotBlank(socialSecurityInfo.getIdCard())) {
            userInfo.setIdCard(privacyMasks.maskIdCard(privacyMasks.decryptPrivacy(socialSecurityInfo.getIdCard())));
        }

        responseDTO.setUserInfo(userInfo);

        //页面显示5种保险，6个月的记录
        int monthCount = 6;
        int limitCount = monthCount * 5;

        List<SocialSecurityRecordDTO> socialSecurityDetailRecordList = socialSecurityDataDubboService.querySocialSecurityDetailList(userId, limitCount);
        if (socialSecurityDetailRecordList == null) {
            return responseDTO;
        }
        List<SocialSecurityResponseDetailVO.MonthInsurance> insurances = new ArrayList<>(30);
        SocialSecurityResponseDetailVO.MonthInsurance monthInsurance = null;
        String month = null;

        for (SocialSecurityRecordDTO record : socialSecurityDetailRecordList) {

            //月份不一样的情况
            if (month != null && !month.equals(record.getMonth())) {
                insurances.add(monthInsurance);

                month = record.getMonth();
                monthInsurance = new SocialSecurityResponseDetailVO.MonthInsurance();
                monthInsurance.setItem(new HashMap<>());
                monthInsurance.setMonth(month);
            }
            //第一次时
            if (month == null) {
                month = record.getMonth();
                monthInsurance = new SocialSecurityResponseDetailVO.MonthInsurance();
                monthInsurance.setItem(new HashMap<>());
                monthInsurance.setMonth(month);
            }

            SocialSecurityResponseDetailVO.Insurance insurance = new SocialSecurityResponseDetailVO.Insurance();
            insurance.setMonthlyCompanyIncome(String.valueOf(record.getMonthlyCompanyIncome()));
            insurance.setMonthlyPersonalIncome(String.valueOf(record.getMonthlyPersonalIncome()));
            insurance.setMonthlyTotalIncome(String.valueOf(bigDecimalAdd(record.getMonthlyCompanyIncome(), record.getMonthlyPersonalIncome())));
            monthInsurance.getItem().put(createSocialTypeName(record.getType()), insurance);

        }
        if (monthInsurance != null) {
            insurances.add(monthInsurance);
        }

        if (insurances.size() > monthCount) {
            List<SocialSecurityResponseDetailVO.MonthInsurance> subList = new ArrayList<>(monthCount);
            for (int i = 0; i < monthCount; i++) {
                subList.add(insurances.get(i));
            }
            Collections.reverse(subList);
            responseDTO.setInsurances(subList);
        } else {
            Collections.reverse(insurances);
            responseDTO.setInsurances(insurances);
        }
        return responseDTO;
    }

    /**
     * 保险类型与名称的映射：保险记录类型（1.工伤保险、2.医疗保险、3.养老保险、4.失业保险、5.生育保险）
     * @param type
     * @return
     */
    private String createSocialTypeName(String type) {
        switch (type) {
            case "1":
                return "accident";
            case "2":
                return "medical";
            case "3":
                return "endowment";
            case "4":
                return "unemployment";
            case "5":
                return "maternity";
            default:
                return "unknown";
        }
    }

    private BigDecimal bigDecimalAdd(BigDecimal numberOne, BigDecimal numberTwo){
        if(numberOne == null){
            return numberTwo;
        }
        if(numberTwo == null){
            return numberOne;
        }
        return numberOne.add(numberTwo);
    }

    @PostMapping("/creditCardAuth")
    @ApiOperation("信用卡授权")
    public Result<ThirdAuthResponseVO> creditCardAuth(@RequestBody(required = false) CreditCardAuthRequestVO creditCardAuthRequestVO, HttpServletRequest httpServletRequest) {
        String userId = PrincipalContext.getUserId();
        String createIp = RequestUtil.getUserRealIP(httpServletRequest);
        log.info("creditCardAuthCreateIp:" + createIp);
        //获取标记
        String mark = null;
        if(creditCardAuthRequestVO != null){
            mark = creditCardAuthRequestVO.getMark();
        }
        ThirdAuthResponseDTO thirdAuthResponseDTO = userAuthCreditCardDubboService.getThirdAuthUrl(userId, createIp, mark);
        if (thirdAuthResponseDTO == null) {
            return Result.with(null);
        }
        ThirdAuthResponseVO vo = new ThirdAuthResponseVO();
        BeanUtils.copyProperties(thirdAuthResponseDTO, vo);
        vo.setStatus(NumberUtils.toInt(thirdAuthResponseDTO.getStatus()));
        if(thirdAuthResponseDTO.getUserDataStatus() != null) {
            vo.setUserDataStatus(Integer.valueOf(thirdAuthResponseDTO.getUserDataStatus()));
        }
        return Result.with(vo);
    }

    @AuthIgnore
    @PostMapping("/creditCardAuthNotifyCallback")
    @ApiOperation("信用卡授权回调")
    public Empty creditCardAuthNotifyCallback(@RequestBody(required = false)CreditCardAuthCallbackVO creditCardAuthCallbackVO) {
        if(creditCardAuthCallbackVO == null
                ||StringUtils.isBlank(creditCardAuthCallbackVO.getBusiData())
                ||StringUtils.isBlank(creditCardAuthCallbackVO.getHeader())
                ||StringUtils.isBlank(creditCardAuthCallbackVO.getSignatureValue())){
            log.info("creditCardAuthNotifyCallback信用卡授权回调参数为空");
            throw new BizException("USR19095");
        }
        String jsonString = JSON.toJSONString(creditCardAuthCallbackVO);
        log.info("creditCardAuthNotifyCallback信用卡授权回调参数：" + jsonString);
        boolean result = userAuthCreditCardDubboService.authCallback(jsonString);
        if(result){
            return Empty.getInstance();
        }
        throw new BizException("USR19095");
    }

    @PostMapping("/educationAuth")
    @ApiOperation("学历授权v5.1.5")
    public Result<ThirdAuthResponseVO> educationAuth(@RequestBody(required = false) CreditCardAuthRequestVO creditCardAuthRequestVO, HttpServletRequest httpServletRequest) {
        String userId = PrincipalContext.getUserId();
        String createIp = RequestUtil.getUserRealIP(httpServletRequest);
        log.info("educationAuthCreateIp:" + createIp);
        //获取标记
        String mark = null;
        if(creditCardAuthRequestVO != null){
            mark = creditCardAuthRequestVO.getMark();
        }
        ThirdAuthResponseDTO thirdAuthResponseDTO = userAuthEducationDubboService.getThirdAuthUrl(userId, createIp, mark);
        if (thirdAuthResponseDTO == null) {
            return Result.with(null);
        }
        ThirdAuthResponseVO vo = new ThirdAuthResponseVO();
        BeanUtils.copyProperties(thirdAuthResponseDTO, vo);
        vo.setStatus(NumberUtils.toInt(thirdAuthResponseDTO.getStatus()));
        if(thirdAuthResponseDTO.getUserDataStatus() != null) {
            vo.setUserDataStatus(Integer.valueOf(thirdAuthResponseDTO.getUserDataStatus()));
        }
        return Result.with(vo);
    }

    @AuthIgnore
    @PostMapping("/educationAuthNotifyCallback")
    @ApiOperation("学历授权回调v5.1.5")
    public Empty educationAuthNotifyCallback(@RequestBody(required = false)CreditCardAuthCallbackVO creditCardAuthCallbackVO) {
        if(creditCardAuthCallbackVO == null
                ||StringUtils.isBlank(creditCardAuthCallbackVO.getBusiData())
                ||StringUtils.isBlank(creditCardAuthCallbackVO.getHeader())
                ||StringUtils.isBlank(creditCardAuthCallbackVO.getSignatureValue())){
            log.info("educationAuthNotifyCallback学历授权回调参数为空");
            throw new BizException("USR19095");
        }
        String jsonString = JSON.toJSONString(creditCardAuthCallbackVO);
        log.info("educationAuthNotifyCallback学历授权回调参数：" + jsonString);
        boolean result = userAuthEducationDubboService.dataCallBack(jsonString);
        if(result){
            return Empty.getInstance();
        }
        throw new BizException("USR19095");
    }

    @PostMapping("/jdAuth")
    @ApiOperation("京东授权v5.1.5")
    public Result<ThirdAuthResponseVO> jdAuth(@RequestBody(required = false) CreditCardAuthRequestVO authRequestVO, HttpServletRequest httpServletRequest) {
        String userId = PrincipalContext.getUserId();
        String createIp = RequestUtil.getUserRealIP(httpServletRequest);
        log.info("jdAuthCreateIp:" + createIp);
        //获取标记
        String mark = null;
        if(authRequestVO != null){
            mark = authRequestVO.getMark();
        }
        ThirdAuthResponseDTO thirdAuthResponseDTO = userAuthJdDubboService.getThirdAuthUrl(userId, createIp, mark);
        if (thirdAuthResponseDTO == null) {
            return Result.with(null);
        }
        ThirdAuthResponseVO vo = new ThirdAuthResponseVO();
        BeanUtils.copyProperties(thirdAuthResponseDTO, vo);
        vo.setStatus(NumberUtils.toInt(thirdAuthResponseDTO.getStatus()));
        if(thirdAuthResponseDTO.getUserDataStatus() != null) {
            vo.setUserDataStatus(Integer.valueOf(thirdAuthResponseDTO.getUserDataStatus()));
        }
        return Result.with(vo);
    }

    @AuthIgnore
    @PostMapping("/jdAuthNotifyCallback")
    @ApiOperation("京东授权回调v5.1.5")
    public Empty jdAuthNotifyCallback(@RequestBody(required = false)CreditCardAuthCallbackVO creditCardAuthCallbackVO) {
        if(creditCardAuthCallbackVO == null
                ||StringUtils.isBlank(creditCardAuthCallbackVO.getBusiData())
                ||StringUtils.isBlank(creditCardAuthCallbackVO.getHeader())
                ||StringUtils.isBlank(creditCardAuthCallbackVO.getSignatureValue())){
            log.info("jdAuthNotifyCallback京东授权回调参数为空");
            throw new BizException("USR19095");
        }
        String jsonString = JSON.toJSONString(creditCardAuthCallbackVO);
        log.info("jdAuthNotifyCallback京东授权回调参数：" + jsonString);
        boolean result = userAuthJdDubboService.authCallback(jsonString);
        if(result){
            return Empty.getInstance();
        }
        throw new BizException("USR19095");
    }

    @PostMapping("/fadadaEnterAuthNonIgnore")
    @ApiOperation("企业法大大授权-无需登录")
    @AuthIgnore
    public Result<FadadaEnterAuthNonIgnoreResponseVO> fadadaEnterAuthNonIgnore(@RequestBody @Valid FadadaEnterAuthNonIgnoreRequestVO requestVO) {
        log.info("fadadaEnterAuthNonIgnore.requestVO={}",JSON.toJSONString(requestVO));

        String customerId = userAuthorizationInfoDubboService.fadadaEnterAuth(requestVO.getOrgId());
        FadadaEnterAuthNonIgnoreResponseVO vo = new FadadaEnterAuthNonIgnoreResponseVO();
        vo.setCustomerId(customerId);
        log.info("fadadaEnterAuthNonIgnore.vo={} end",JSON.toJSONString(vo));
        return Result.with(vo);
    }

    @PostMapping("/tbAuth")
    @ApiOperation("淘宝授权成功通知（客户端通知接口）v5.5.8")
    public Empty tbAuth(@RequestBody(required = false) TbAuthNotifyRequestVO authRequestVO, HttpServletRequest httpServletRequest) {
        String userId = PrincipalContext.getUserId();
        log.info("tbAuth授权请求参数:userId={},param={}", userId, JSON.toJSONString(authRequestVO));
        if(authRequestVO == null || StringUtils.isBlank(authRequestVO.getSucessFlag())){
            //请求参数错误
            throw new BizException("USR11009");
        }
        //修改用户淘宝授权状态为已授权
        DataStatusResponseDTO taobaoAuthStatus = userStatusDubboService.getByUserIdAndType(userId, UserDataTypeEnum.TAOBAO_AUTHORIZE);

        if(taobaoAuthStatus != null){
             //已授权或已验证状态，直接返回
             if(UserDataStatusEnum.TaobaoStatus.ALREADY_CREDIT.getStatus().equals(taobaoAuthStatus.getDataStatus())
                    ||UserDataStatusEnum.TaobaoStatus.GETSUCCESS.getStatus().equals(taobaoAuthStatus.getDataStatus())) {
                 log.info("tbAuth授权是已授权，直接返回:userId={},status={}", userId, taobaoAuthStatus.getDataStatus());
                 return Empty.getInstance();
             }
        }

        //成功标识：透传第三方的code: 0授权成功，其他值授权失败
        String sucessFlag = "0";

        if(sucessFlag.equals(authRequestVO.getSucessFlag())) {
            DataStatusRequestDTO requestDTO = new DataStatusRequestDTO();
            requestDTO.setDataType(UserDataTypeEnum.TAOBAO_AUTHORIZE.getValue());
            requestDTO.setUserId(userId);
            requestDTO.setDataStatus(UserDataStatusEnum.TaobaoStatus.ALREADY_CREDIT.getStatus());
            userStatusDubboService.saveDataStatusByUserIdAndType(requestDTO);
            log.info("tbAuth授权状态修改成功:userId={},status={}", userId, UserDataStatusEnum.TaobaoStatus.ALREADY_CREDIT.getStatus());
        }else{
            log.info("淘宝授权回调状态为错误userId={},sucessFlag={},taskId={}", userId, authRequestVO.getSucessFlag(), authRequestVO.getTaskId());
        }
        return Empty.getInstance();
    }
}
